--SELECT *FROM FN_LOAD_PROCESS_STEP_BIN_NUMBERS(1647) ORDER BY CONVERT(INT,SUBSTRING(BIN_NUMBER,4,LEN(LTRIM(RTRIM(BIN_NUMBER)))))
ALTER FUNCTION FN_LOAD_PROCESS_STEP_BIN_NUMBERS( @PROCESS_STEP_ID INT )
RETURNS @FN_RESULTS TABLE( BIN_NUMBER VARCHAR(10) )
AS
BEGIN
	DECLARE @PS_TYPE_NAME VARCHAR(20)
	SELECT @PS_TYPE_NAME = PS_TYPE_NAME FROM PROCESS_STEP WHERE PROCESSSTEP_ID = @PROCESS_STEP_ID
	IF ( @PS_TYPE_NAME = 'SORT' )
	 BEGIN
		INSERT INTO @FN_RESULTS 
			SELECT WSBT_BIN_NUMBER FROM WIP_STEP_BIN_TABLE WHERE PROCESSSTEP_ID = @PROCESS_STEP_ID AND WSBT_BIN_TYPE = 'Accept' ORDER BY CONVERT(INT,SUBSTRING(WSBT_BIN_NUMBER,4,LEN(LTRIM(RTRIM(WSBT_BIN_NUMBER)))))
	 END
	ELSE IF ( @PS_TYPE_NAME = 'Die Bank' )
	 BEGIN
		INSERT INTO @FN_RESULTS
			SELECT DISTINCT Bin_Number FROM Assembly_Bin_Mapping WHERE Assm_ProcessStep_ID IN ( SELECT Next_ProcessStep_ID FROM Process_Step_Traverse_Table WHERE ProcessStep_ID = @PROCESS_STEP_ID ) AND Bin_ProcessStep_ID = (SELECT TOP 1 PROCESSSTEP_ID FROM FN_GET_PROCESS_FLOWS_BY_PROCESSSTEP_ID (@PROCESS_STEP_ID,0) WHERE PS_TYPE_NAME = 'SORT')
		INSERT INTO @FN_RESULTS
			SELECT BIN_NUMBER FROM Wip_Flush_Bin_Setup_Table WBST WHERE WBST.ProcessStep_ID = @PROCESS_STEP_ID AND WBST.BIN_NUMBER NOT IN ( SELECT BIN_NUMBER FROM @FN_RESULTS ) AND WBST.Bin_Value > 0
	 END

RETURN

END